3 * Cache of the contents of localisation files.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use Cdb\Reader
as CdbReader
;
24 use Cdb\Writer
as CdbWriter
;
25 use CLDRPluralRuleParser\Evaluator
;
26 use CLDRPluralRuleParser\Error
as CLDRPluralRuleError
;
27 use MediaWiki\MediaWikiServices
;
30 * Class for caching the contents of localisation files, Messages*.php
33 * An instance of this class is available using Language::getLocalisationCache().
35 * The values retrieved from here are merged, containing items from extension
36 * files, core messages files and the language fallback sequence (e.g. zh-cn ->
37 * zh-hans -> en ). Some common errors are corrected, for example namespace
38 * names with spaces instead of underscores, but heavyweight processing, such
39 * as grammatical transformation, is done by the caller.
41 class LocalisationCache
{
44 /** Configuration associative array */
48 * True if recaching should only be done on an explicit call to recache().
49 * Setting this reduces the overhead of cache freshness checking, which
50 * requires doing a stat() for every extension i18n file.
52 private $manualRecache = false;
55 * True to treat all files as expired until they are regenerated by this object.
57 private $forceRecache = false;
60 * The cache data. 3-d array, where the first key is the language code,
61 * the second key is the item key e.g. 'messages', and the third key is
62 * an item specific subkey index. Some items are not arrays and so for those
63 * items, there are no subkeys.
68 * The persistent store object. An instance of LCStore.
75 * A 2-d associative array, code/key, where presence indicates that the item
76 * is loaded. Value arbitrary.
78 * For split items, if set, this indicates that all of the subitems have been
81 private $loadedItems = [];
84 * A 3-d associative array, code/key/subkey, where presence indicates that
85 * the subitem is loaded. Only used for the split items, i.e. messages.
87 private $loadedSubitems = [];
90 * An array where presence of a key indicates that that language has been
91 * initialised. Initialisation includes checking for cache expiry and doing
92 * any necessary updates.
94 private $initialisedLangs = [];
97 * An array mapping non-existent pseudo-languages to fallback languages. This
98 * is filled by initShallowFallback() when data is requested from a language
99 * that lacks a Messages*.php file.
101 private $shallowFallbacks = [];
104 * An array where the keys are codes that have been recached by this instance.
106 private $recachedLangs = [];
111 static public $allKeys = [
112 'fallback', 'namespaceNames', 'bookstoreList',
113 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns', 'digitTransformTable',
114 'separatorTransformTable', 'fallback8bitEncoding', 'linkPrefixExtension',
115 'linkTrail', 'linkPrefixCharset', 'namespaceAliases',
116 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
117 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases',
118 'imageFiles', 'preloadedMessages', 'namespaceGenderAliases',
119 'digitGroupingPattern', 'pluralRules', 'pluralRuleTypes', 'compiledPluralRules',
123 * Keys for items which consist of associative arrays, which may be merged
124 * by a fallback sequence.
126 static public $mergeableMapKeys = [ 'messages', 'namespaceNames',
127 'namespaceAliases', 'dateFormats', 'imageFiles', 'preloadedMessages'
131 * Keys for items which are a numbered array.
133 static public $mergeableListKeys = [ 'extraUserToggles' ];
136 * Keys for items which contain an array of arrays of equivalent aliases
137 * for each subitem. The aliases may be merged by a fallback sequence.
139 static public $mergeableAliasListKeys = [ 'specialPageAliases' ];
142 * Keys for items which contain an associative array, and may be merged if
143 * the primary value contains the special array key "inherit". That array
144 * key is removed after the first merge.
146 static public $optionalMergeKeys = [ 'bookstoreList' ];
149 * Keys for items that are formatted like $magicWords
151 static public $magicWordKeys = [ 'magicWords' ];
154 * Keys for items where the subitems are stored in the backend separately.
156 static public $splitKeys = [ 'messages' ];
159 * Keys which are loaded automatically by initLanguage()
161 static public $preloadedKeys = [ 'dateFormats', 'namespaceNames' ];
164 * Associative array of cached plural rules. The key is the language code,
165 * the value is an array of plural rules for that language.
167 private $pluralRules = null;
170 * Associative array of cached plural rule types. The key is the language
171 * code, the value is an array of plural rule types for that language. For
172 * example, $pluralRuleTypes['ar'] = ['zero', 'one', 'two', 'few', 'many'].
173 * The index for each rule type matches the index for the rule in
174 * $pluralRules, thus allowing correlation between the two. The reason we
175 * don't just use the type names as the keys in $pluralRules is because
176 * Language::convertPlural applies the rules based on numeric order (or
177 * explicit numeric parameter), not based on the name of the rule type. For
178 * example, {{plural:count|wordform1|wordform2|wordform3}}, rather than
179 * {{plural:count|one=wordform1|two=wordform2|many=wordform3}}.
181 private $pluralRuleTypes = null;
183 private $mergeableKeys = null;
186 * For constructor parameters, see the documentation in DefaultSettings.php
187 * for $wgLocalisationCacheConf.
190 * @throws MWException
192 function __construct( $conf ) {
193 global $wgCacheDirectory;
197 if ( !empty( $conf['storeClass'] ) ) {
198 $storeClass = $conf['storeClass'];
200 switch ( $conf['store'] ) {
203 $storeClass = 'LCStoreCDB';
206 $storeClass = 'LCStoreDB';
209 $storeClass = 'LCStoreStaticArray';
212 if ( !empty( $conf['storeDirectory'] ) ) {
213 $storeClass = 'LCStoreCDB';
214 } elseif ( $wgCacheDirectory ) {
215 $storeConf['directory'] = $wgCacheDirectory;
216 $storeClass = 'LCStoreCDB';
218 $storeClass = 'LCStoreDB';
222 throw new MWException(
223 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.'
228 wfDebugLog( 'caches', static::class . ": using store $storeClass" );
229 if ( !empty( $conf['storeDirectory'] ) ) {
230 $storeConf['directory'] = $conf['storeDirectory'];
233 $this->store
= new $storeClass( $storeConf );
234 foreach ( [ 'manualRecache', 'forceRecache' ] as $var ) {
235 if ( isset( $conf[$var] ) ) {
236 $this->$var = $conf[$var];
242 * Returns true if the given key is mergeable, that is, if it is an associative
243 * array which can be merged through a fallback sequence.
247 public function isMergeableKey( $key ) {
248 if ( $this->mergeableKeys
=== null ) {
249 $this->mergeableKeys
= array_flip( array_merge(
250 self
::$mergeableMapKeys,
251 self
::$mergeableListKeys,
252 self
::$mergeableAliasListKeys,
253 self
::$optionalMergeKeys,
258 return isset( $this->mergeableKeys
[$key] );
264 * Warning: this may be slow for split items (messages), since it will
265 * need to fetch all of the subitems from the cache individually.
266 * @param string $code
270 public function getItem( $code, $key ) {
271 if ( !isset( $this->loadedItems
[$code][$key] ) ) {
272 $this->loadItem( $code, $key );
275 if ( $key === 'fallback' && isset( $this->shallowFallbacks
[$code] ) ) {
276 return $this->shallowFallbacks
[$code];
279 return $this->data
[$code][$key];
283 * Get a subitem, for instance a single message for a given language.
284 * @param string $code
286 * @param string $subkey
289 public function getSubitem( $code, $key, $subkey ) {
290 if ( !isset( $this->loadedSubitems
[$code][$key][$subkey] ) &&
291 !isset( $this->loadedItems
[$code][$key] )
293 $this->loadSubitem( $code, $key, $subkey );
296 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
297 return $this->data
[$code][$key][$subkey];
304 * Get the list of subitem keys for a given item.
306 * This is faster than array_keys($lc->getItem(...)) for the items listed in
309 * Will return null if the item is not found, or false if the item is not an
311 * @param string $code
313 * @return bool|null|string|string[]
315 public function getSubitemList( $code, $key ) {
316 if ( in_array( $key, self
::$splitKeys ) ) {
317 return $this->getSubitem( $code, 'list', $key );
319 $item = $this->getItem( $code, $key );
320 if ( is_array( $item ) ) {
321 return array_keys( $item );
329 * Load an item into the cache.
330 * @param string $code
333 protected function loadItem( $code, $key ) {
334 if ( !isset( $this->initialisedLangs
[$code] ) ) {
335 $this->initLanguage( $code );
338 // Check to see if initLanguage() loaded it for us
339 if ( isset( $this->loadedItems
[$code][$key] ) ) {
343 if ( isset( $this->shallowFallbacks
[$code] ) ) {
344 $this->loadItem( $this->shallowFallbacks
[$code], $key );
349 if ( in_array( $key, self
::$splitKeys ) ) {
350 $subkeyList = $this->getSubitem( $code, 'list', $key );
351 foreach ( $subkeyList as $subkey ) {
352 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
355 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
358 $this->data
[$code][$key] = $this->store
->get( $code, $key );
361 $this->loadedItems
[$code][$key] = true;
365 * Load a subitem into the cache
366 * @param string $code
368 * @param string $subkey
370 protected function loadSubitem( $code, $key, $subkey ) {
371 if ( !in_array( $key, self
::$splitKeys ) ) {
372 $this->loadItem( $code, $key );
377 if ( !isset( $this->initialisedLangs
[$code] ) ) {
378 $this->initLanguage( $code );
381 // Check to see if initLanguage() loaded it for us
382 if ( isset( $this->loadedItems
[$code][$key] ) ||
383 isset( $this->loadedSubitems
[$code][$key][$subkey] )
388 if ( isset( $this->shallowFallbacks
[$code] ) ) {
389 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
394 $value = $this->store
->get( $code, "$key:$subkey" );
395 $this->data
[$code][$key][$subkey] = $value;
396 $this->loadedSubitems
[$code][$key][$subkey] = true;
400 * Returns true if the cache identified by $code is missing or expired.
402 * @param string $code
406 public function isExpired( $code ) {
407 if ( $this->forceRecache
&& !isset( $this->recachedLangs
[$code] ) ) {
408 wfDebug( __METHOD__
. "($code): forced reload\n" );
413 $deps = $this->store
->get( $code, 'deps' );
414 $keys = $this->store
->get( $code, 'list' );
415 $preload = $this->store
->get( $code, 'preload' );
416 // Different keys may expire separately for some stores
417 if ( $deps === null ||
$keys === null ||
$preload === null ) {
418 wfDebug( __METHOD__
. "($code): cache missing, need to make one\n" );
423 foreach ( $deps as $dep ) {
424 // Because we're unserializing stuff from cache, we
425 // could receive objects of classes that don't exist
426 // anymore (e.g. uninstalled extensions)
427 // When this happens, always expire the cache
428 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
429 wfDebug( __METHOD__
. "($code): cache for $code expired due to " .
430 get_class( $dep ) . "\n" );
440 * Initialise a language in this object. Rebuild the cache if necessary.
441 * @param string $code
442 * @throws MWException
444 protected function initLanguage( $code ) {
445 if ( isset( $this->initialisedLangs
[$code] ) ) {
449 $this->initialisedLangs
[$code] = true;
451 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
452 if ( !Language
::isValidBuiltInCode( $code ) ) {
453 $this->initShallowFallback( $code, 'en' );
458 # Recache the data if necessary
459 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
460 if ( Language
::isSupportedLanguage( $code ) ) {
461 $this->recache( $code );
462 } elseif ( $code === 'en' ) {
463 throw new MWException( 'MessagesEn.php is missing.' );
465 $this->initShallowFallback( $code, 'en' );
472 $preload = $this->getItem( $code, 'preload' );
473 if ( $preload === null ) {
474 if ( $this->manualRecache
) {
475 // No Messages*.php file. Do shallow fallback to en.
476 if ( $code === 'en' ) {
477 throw new MWException( 'No localisation cache found for English. ' .
478 'Please run maintenance/rebuildLocalisationCache.php.' );
480 $this->initShallowFallback( $code, 'en' );
484 throw new MWException( 'Invalid or missing localisation cache.' );
487 $this->data
[$code] = $preload;
488 foreach ( $preload as $key => $item ) {
489 if ( in_array( $key, self
::$splitKeys ) ) {
490 foreach ( $item as $subkey => $subitem ) {
491 $this->loadedSubitems
[$code][$key][$subkey] = true;
494 $this->loadedItems
[$code][$key] = true;
500 * Create a fallback from one language to another, without creating a
501 * complete persistent cache.
502 * @param string $primaryCode
503 * @param string $fallbackCode
505 public function initShallowFallback( $primaryCode, $fallbackCode ) {
506 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
507 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
508 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
509 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
513 * Read a PHP file containing localisation data.
514 * @param string $_fileName
515 * @param string $_fileType
516 * @throws MWException
519 protected function readPHPFile( $_fileName, $_fileType ) {
520 // Disable APC caching
521 MediaWiki\
suppressWarnings();
522 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
523 MediaWiki\restoreWarnings
();
527 MediaWiki\
suppressWarnings();
528 ini_set( 'apc.cache_by_default', $_apcEnabled );
529 MediaWiki\restoreWarnings
();
531 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
532 $data = compact( self
::$allKeys );
533 } elseif ( $_fileType == 'aliases' ) {
534 $data = compact( 'aliases' );
536 throw new MWException( __METHOD__
. ": Invalid file type: $_fileType" );
543 * Read a JSON file containing localisation messages.
544 * @param string $fileName Name of file to read
545 * @throws MWException If there is a syntax error in the JSON file
546 * @return array Array with a 'messages' key, or empty array if the file doesn't exist
548 public function readJSONFile( $fileName ) {
549 if ( !is_readable( $fileName ) ) {
553 $json = file_get_contents( $fileName );
554 if ( $json === false ) {
558 $data = FormatJson
::decode( $json, true );
559 if ( $data === null ) {
560 throw new MWException( __METHOD__
. ": Invalid JSON file: $fileName" );
563 // Remove keys starting with '@', they're reserved for metadata and non-message data
564 foreach ( $data as $key => $unused ) {
565 if ( $key === '' ||
$key[0] === '@' ) {
566 unset( $data[$key] );
570 // The JSON format only supports messages, none of the other variables, so wrap the data
571 return [ 'messages' => $data ];
575 * Get the compiled plural rules for a given language from the XML files.
577 * @param string $code
580 public function getCompiledPluralRules( $code ) {
581 $rules = $this->getPluralRules( $code );
582 if ( $rules === null ) {
586 $compiledRules = Evaluator
::compile( $rules );
587 } catch ( CLDRPluralRuleError
$e ) {
588 wfDebugLog( 'l10n', $e->getMessage() );
593 return $compiledRules;
597 * Get the plural rules for a given language from the XML files.
600 * @param string $code
603 public function getPluralRules( $code ) {
604 if ( $this->pluralRules
=== null ) {
605 $this->loadPluralFiles();
607 if ( !isset( $this->pluralRules
[$code] ) ) {
610 return $this->pluralRules
[$code];
615 * Get the plural rule types for a given language from the XML files.
618 * @param string $code
621 public function getPluralRuleTypes( $code ) {
622 if ( $this->pluralRuleTypes
=== null ) {
623 $this->loadPluralFiles();
625 if ( !isset( $this->pluralRuleTypes
[$code] ) ) {
628 return $this->pluralRuleTypes
[$code];
633 * Load the plural XML files.
635 protected function loadPluralFiles() {
637 $cldrPlural = "$IP/languages/data/plurals.xml";
638 $mwPlural = "$IP/languages/data/plurals-mediawiki.xml";
639 // Load CLDR plural rules
640 $this->loadPluralFile( $cldrPlural );
641 if ( file_exists( $mwPlural ) ) {
642 // Override or extend
643 $this->loadPluralFile( $mwPlural );
648 * Load a plural XML file with the given filename, compile the relevant
649 * rules, and save the compiled rules in a process-local cache.
651 * @param string $fileName
652 * @throws MWException
654 protected function loadPluralFile( $fileName ) {
655 // Use file_get_contents instead of DOMDocument::load (T58439)
656 $xml = file_get_contents( $fileName );
658 throw new MWException( "Unable to read plurals file $fileName" );
660 $doc = new DOMDocument
;
661 $doc->loadXML( $xml );
662 $rulesets = $doc->getElementsByTagName( "pluralRules" );
663 foreach ( $rulesets as $ruleset ) {
664 $codes = $ruleset->getAttribute( 'locales' );
667 $ruleElements = $ruleset->getElementsByTagName( "pluralRule" );
668 foreach ( $ruleElements as $elt ) {
669 $ruleType = $elt->getAttribute( 'count' );
670 if ( $ruleType === 'other' ) {
671 // Don't record "other" rules, which have an empty condition
674 $rules[] = $elt->nodeValue
;
675 $ruleTypes[] = $ruleType;
677 foreach ( explode( ' ', $codes ) as $code ) {
678 $this->pluralRules
[$code] = $rules;
679 $this->pluralRuleTypes
[$code] = $ruleTypes;
685 * Read the data from the source files for a given language, and register
686 * the relevant dependencies in the $deps array. If the localisation
687 * exists, the data array is returned, otherwise false is returned.
689 * @param string $code
690 * @param array &$deps
693 protected function readSourceFilesAndRegisterDeps( $code, &$deps ) {
696 // This reads in the PHP i18n file with non-messages l10n data
697 $fileName = Language
::getMessagesFileName( $code );
698 if ( !file_exists( $fileName ) ) {
701 $deps[] = new FileDependency( $fileName );
702 $data = $this->readPHPFile( $fileName, 'core' );
705 # Load CLDR plural rules for JavaScript
706 $data['pluralRules'] = $this->getPluralRules( $code );
708 $data['compiledPluralRules'] = $this->getCompiledPluralRules( $code );
709 # Load plural rule types
710 $data['pluralRuleTypes'] = $this->getPluralRuleTypes( $code );
712 $deps['plurals'] = new FileDependency( "$IP/languages/data/plurals.xml" );
713 $deps['plurals-mw'] = new FileDependency( "$IP/languages/data/plurals-mediawiki.xml" );
719 * Merge two localisation values, a primary and a fallback, overwriting the
720 * primary value in place.
722 * @param mixed &$value
723 * @param mixed $fallbackValue
725 protected function mergeItem( $key, &$value, $fallbackValue ) {
726 if ( !is_null( $value ) ) {
727 if ( !is_null( $fallbackValue ) ) {
728 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
729 $value = $value +
$fallbackValue;
730 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
731 $value = array_unique( array_merge( $fallbackValue, $value ) );
732 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
733 $value = array_merge_recursive( $value, $fallbackValue );
734 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
735 if ( !empty( $value['inherit'] ) ) {
736 $value = array_merge( $fallbackValue, $value );
739 if ( isset( $value['inherit'] ) ) {
740 unset( $value['inherit'] );
742 } elseif ( in_array( $key, self
::$magicWordKeys ) ) {
743 $this->mergeMagicWords( $value, $fallbackValue );
747 $value = $fallbackValue;
752 * @param mixed &$value
753 * @param mixed $fallbackValue
755 protected function mergeMagicWords( &$value, $fallbackValue ) {
756 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
757 if ( !isset( $value[$magicName] ) ) {
758 $value[$magicName] = $fallbackInfo;
760 $oldSynonyms = array_slice( $fallbackInfo, 1 );
761 $newSynonyms = array_slice( $value[$magicName], 1 );
762 $synonyms = array_values( array_unique( array_merge(
763 $newSynonyms, $oldSynonyms ) ) );
764 $value[$magicName] = array_merge( [ $fallbackInfo[0] ], $synonyms );
770 * Given an array mapping language code to localisation value, such as is
771 * found in extension *.i18n.php files, iterate through a fallback sequence
772 * to merge the given data with an existing primary value.
774 * Returns true if any data from the extension array was used, false
776 * @param array $codeSequence
778 * @param mixed &$value
779 * @param mixed $fallbackValue
782 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
784 foreach ( $codeSequence as $code ) {
785 if ( isset( $fallbackValue[$code] ) ) {
786 $this->mergeItem( $key, $value, $fallbackValue[$code] );
795 * Gets the combined list of messages dirs from
796 * core and extensions
801 public function getMessagesDirs() {
804 $config = MediaWikiServices
::getInstance()->getMainConfig();
805 $messagesDirs = $config->get( 'MessagesDirs' );
807 'core' => "$IP/languages/i18n",
808 'api' => "$IP/includes/api/i18n",
809 'oojs-ui' => "$IP/resources/lib/oojs-ui/i18n",
814 * Load localisation data for a given language for both core and extensions
815 * and save it to the persistent cache store and the process cache
816 * @param string $code
817 * @throws MWException
819 public function recache( $code ) {
820 global $wgExtensionMessagesFiles;
823 throw new MWException( "Invalid language code requested" );
825 $this->recachedLangs
[$code] = true;
828 $initialData = array_fill_keys( self
::$allKeys, null );
829 $coreData = $initialData;
832 # Load the primary localisation from the source file
833 $data = $this->readSourceFilesAndRegisterDeps( $code, $deps );
834 if ( $data === false ) {
835 wfDebug( __METHOD__
. ": no localisation file for $code, using fallback to en\n" );
836 $coreData['fallback'] = 'en';
838 wfDebug( __METHOD__
. ": got localisation for $code from source\n" );
840 # Merge primary localisation
841 foreach ( $data as $key => $value ) {
842 $this->mergeItem( $key, $coreData[$key], $value );
846 # Fill in the fallback if it's not there already
847 if ( is_null( $coreData['fallback'] ) ) {
848 $coreData['fallback'] = $code === 'en' ?
false : 'en';
850 if ( $coreData['fallback'] === false ) {
851 $coreData['fallbackSequence'] = [];
853 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
854 $len = count( $coreData['fallbackSequence'] );
856 # Ensure that the sequence ends at en
857 if ( $coreData['fallbackSequence'][$len - 1] !== 'en' ) {
858 $coreData['fallbackSequence'][] = 'en';
862 $codeSequence = array_merge( [ $code ], $coreData['fallbackSequence'] );
863 $messageDirs = $this->getMessagesDirs();
865 # Load non-JSON localisation data for extensions
866 $extensionData = array_fill_keys( $codeSequence, $initialData );
867 foreach ( $wgExtensionMessagesFiles as $extension => $fileName ) {
868 if ( isset( $messageDirs[$extension] ) ) {
869 # This extension has JSON message data; skip the PHP shim
873 $data = $this->readPHPFile( $fileName, 'extension' );
876 foreach ( $data as $key => $item ) {
877 foreach ( $codeSequence as $csCode ) {
878 if ( isset( $item[$csCode] ) ) {
879 $this->mergeItem( $key, $extensionData[$csCode][$key], $item[$csCode] );
886 $deps[] = new FileDependency( $fileName );
890 # Load the localisation data for each fallback, then merge it into the full array
891 $allData = $initialData;
892 foreach ( $codeSequence as $csCode ) {
893 $csData = $initialData;
895 # Load core messages and the extension localisations.
896 foreach ( $messageDirs as $dirs ) {
897 foreach ( (array)$dirs as $dir ) {
898 $fileName = "$dir/$csCode.json";
899 $data = $this->readJSONFile( $fileName );
901 foreach ( $data as $key => $item ) {
902 $this->mergeItem( $key, $csData[$key], $item );
905 $deps[] = new FileDependency( $fileName );
909 # Merge non-JSON extension data
910 if ( isset( $extensionData[$csCode] ) ) {
911 foreach ( $extensionData[$csCode] as $key => $item ) {
912 $this->mergeItem( $key, $csData[$key], $item );
916 if ( $csCode === $code ) {
917 # Merge core data into extension data
918 foreach ( $coreData as $key => $item ) {
919 $this->mergeItem( $key, $csData[$key], $item );
922 # Load the secondary localisation from the source file to
923 # avoid infinite cycles on cyclic fallbacks
924 $fbData = $this->readSourceFilesAndRegisterDeps( $csCode, $deps );
925 if ( $fbData !== false ) {
926 # Only merge the keys that make sense to merge
927 foreach ( self
::$allKeys as $key ) {
928 if ( !isset( $fbData[$key] ) ) {
932 if ( is_null( $coreData[$key] ) ||
$this->isMergeableKey( $key ) ) {
933 $this->mergeItem( $key, $csData[$key], $fbData[$key] );
939 # Allow extensions an opportunity to adjust the data for this
941 Hooks
::run( 'LocalisationCacheRecacheFallback', [ $this, $csCode, &$csData ] );
943 # Merge the data for this fallback into the final array
944 if ( $csCode === $code ) {
947 foreach ( self
::$allKeys as $key ) {
948 if ( !isset( $csData[$key] ) ) {
952 if ( is_null( $allData[$key] ) ||
$this->isMergeableKey( $key ) ) {
953 $this->mergeItem( $key, $allData[$key], $csData[$key] );
959 # Add cache dependencies for any referenced globals
960 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
961 // The 'MessagesDirs' config setting is used in LocalisationCache::getMessagesDirs().
962 // We use the key 'wgMessagesDirs' for historical reasons.
963 $deps['wgMessagesDirs'] = new MainConfigDependency( 'MessagesDirs' );
964 $deps['version'] = new ConstantDependency( 'LocalisationCache::VERSION' );
966 # Add dependencies to the cache entry
967 $allData['deps'] = $deps;
969 # Replace spaces with underscores in namespace names
970 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
972 # And do the same for special page aliases. $page is an array.
973 foreach ( $allData['specialPageAliases'] as &$page ) {
974 $page = str_replace( ' ', '_', $page );
976 # Decouple the reference to prevent accidental damage
979 # If there were no plural rules, return an empty array
980 if ( $allData['pluralRules'] === null ) {
981 $allData['pluralRules'] = [];
983 if ( $allData['compiledPluralRules'] === null ) {
984 $allData['compiledPluralRules'] = [];
986 # If there were no plural rule types, return an empty array
987 if ( $allData['pluralRuleTypes'] === null ) {
988 $allData['pluralRuleTypes'] = [];
992 $allData['list'] = [];
993 foreach ( self
::$splitKeys as $key ) {
994 $allData['list'][$key] = array_keys( $allData[$key] );
998 Hooks
::run( 'LocalisationCacheRecache', [ $this, $code, &$allData, &$purgeBlobs ] );
1000 if ( is_null( $allData['namespaceNames'] ) ) {
1001 throw new MWException( __METHOD__
. ': Localisation data failed sanity check! ' .
1002 'Check that your languages/messages/MessagesEn.php file is intact.' );
1005 # Set the preload key
1006 $allData['preload'] = $this->buildPreload( $allData );
1008 # Save to the process cache and register the items loaded
1009 $this->data
[$code] = $allData;
1010 foreach ( $allData as $key => $item ) {
1011 $this->loadedItems
[$code][$key] = true;
1014 # Save to the persistent cache
1015 $this->store
->startWrite( $code );
1016 foreach ( $allData as $key => $value ) {
1017 if ( in_array( $key, self
::$splitKeys ) ) {
1018 foreach ( $value as $subkey => $subvalue ) {
1019 $this->store
->set( "$key:$subkey", $subvalue );
1022 $this->store
->set( $key, $value );
1025 $this->store
->finishWrite();
1027 # Clear out the MessageBlobStore
1028 # HACK: If using a null (i.e. disabled) storage backend, we
1029 # can't write to the MessageBlobStore either
1030 if ( $purgeBlobs && !$this->store
instanceof LCStoreNull
) {
1031 $blobStore = new MessageBlobStore();
1032 $blobStore->clear();
1037 * Build the preload item from the given pre-cache data.
1039 * The preload item will be loaded automatically, improving performance
1040 * for the commonly-requested items it contains.
1041 * @param array $data
1044 protected function buildPreload( $data ) {
1045 $preload = [ 'messages' => [] ];
1046 foreach ( self
::$preloadedKeys as $key ) {
1047 $preload[$key] = $data[$key];
1050 foreach ( $data['preloadedMessages'] as $subkey ) {
1051 if ( isset( $data['messages'][$subkey] ) ) {
1052 $subitem = $data['messages'][$subkey];
1056 $preload['messages'][$subkey] = $subitem;
1063 * Unload the data for a given language from the object cache.
1064 * Reduces memory usage.
1065 * @param string $code
1067 public function unload( $code ) {
1068 unset( $this->data
[$code] );
1069 unset( $this->loadedItems
[$code] );
1070 unset( $this->loadedSubitems
[$code] );
1071 unset( $this->initialisedLangs
[$code] );
1072 unset( $this->shallowFallbacks
[$code] );
1074 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
1075 if ( $fbCode === $code ) {
1076 $this->unload( $shallowCode );
1084 public function unloadAll() {
1085 foreach ( $this->initialisedLangs
as $lang => $unused ) {
1086 $this->unload( $lang );
1091 * Disable the storage backend
1093 public function disableBackend() {
1094 $this->store
= new LCStoreNull
;
1095 $this->manualRecache
= false;